<template>
  <div class="container-box main-box">
    <CommonCrud ref="crudRef" :showEdit="false" :showAdd="false" :showDelete="false" @search="handleSearch">
      <el-table-column prop="name" label="表名称" />
      <el-table-column prop="collection" label="表介绍"></el-table-column>
      <template #operation="{ row }">
        <el-button type="primary" link @click="codeGenerator(row)">
          生成代码
        </el-button>
      </template>
    </CommonCrud>
    <div class="code">
      <div class="code-box">
        <el-radio-group v-model="radio">
          <el-radio :value="1">页面</el-radio>
          <el-radio :value="2">API</el-radio>
        </el-radio-group>
        <CodeHighlight :code="radio == 1 ? htmlCode : apiCode" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import CommonCrud from "@/components/CommonCrud/index.vue"
import { getModelList, getModel } from "@/api/code"
import { getTemplate } from "./cfg/index.ts";
import { getApiList } from "./cfg/api";
import CodeHighlight from "@/components/CodeHighlight/index.vue"
interface TableData {
  id: number
  name: string
  collection: string
  fields: FieldData[]
  create_time?: string
  update_time?: string
}

interface FieldData {
  name: string
  type: string
  required: boolean
  default?: any
  description?: string
}

interface ApiResponse<T> {
  code: number
  data: T
  message: string
}

const crudRef = ref()
const radio = ref(1)
// 获取列表
const handleSearch = async (params: any) => {
  try {
    crudRef.value.loading = true
    const res = (await getModelList(params)) as ApiResponse<{
      list: TableData[]
      total: number
    }>
    if (res.code === 200) {
      crudRef.value.tableData = res.data.data
      crudRef.value.total = res.data.total
    }
  } finally {
    crudRef.value.loading = false
  }
}

const htmlCode = ref('')
const apiCode = ref('')
// 生成代码
const codeGenerator = async (row: TableData) => {
  const { code, data } = await getModel(row.name)
  if (code === 200) {
    htmlCode.value = getTemplate(data)
    apiCode.value = getApiList(data)
  }

}

onMounted(() => {
  handleSearch({})
})
</script>

<style scoped lang="scss">
.main-box {
  height: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 20px;

  .code {
    height: 100%;
    overflow: scroll;
    background-color: #fff;
    border-radius: 20px;
    padding: 20px;

    .code-box {
      height: 100%;
      overflow: scroll;

    }
  }
}
</style>
